﻿namespace WebApi2.Common
{
    public class PluginsManagement
    {
        private readonly IServiceProvider serviceProvider;
        Dictionary<string, Type> dict = new Dictionary<string, Type>();
        public PluginsManagement(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }
        public IPluginClass GetPluginClass(string name)
        {
            var type = dict[name];
            return Activator.CreateInstance(type, serviceProvider) as IPluginClass;
        }
        public void RegisterPluginClass<T>(string name) where T : IPluginClass
        {
            dict.Add(name, typeof(T));
        }
    }

    public interface IPluginClass
    {
        void ConsoleWrite();
    }
    public class A : IPluginClass
    {
        private readonly ILogger<A> logger;

        public A(IServiceProvider serviceProvider)
        {
            logger = serviceProvider.GetRequiredService<ILogger<A>>();
        }
        public void ConsoleWrite()
        {
            logger.LogInformation("A写日志");
        }
    }
    public class B : IPluginClass
    {
        private readonly ILogger<A> logger;
        private readonly A a;
        public B(IServiceProvider serviceProvider)
        {
            logger = serviceProvider.GetRequiredService<ILogger<A>>();
            a = (A)serviceProvider.GetRequiredService<PluginsManagement>().GetPluginClass("a");
        }
        public B(A a)
        {
            this.a = a;
        }

        public void ConsoleWrite()
        {
            a.ConsoleWrite();
            logger.LogInformation("B写日志");
        }
    }
}
